package org.teamswift.crow.rbac.security.permission;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.teamswift.crow.rbac.annotation.OrganizationLimited;
import org.teamswift.crow.rbac.common.CrowOrgLimitedEntity;
import org.teamswift.crow.rbac.entity.CrowUser;
import org.teamswift.crow.rest.handler.IRequestBodyResolver;
import org.teamswift.crow.rest.handler.requestParams.FilterItem;
import org.teamswift.crow.rest.handler.requestParams.RequestBodyResolved;

import java.util.List;

@Component
public class CrowRbacRequestBodyResolver implements IRequestBodyResolver {

    @Override
    public void handle(RequestBodyResolved body) {

        Subject subject = SecurityUtils.getSubject();
        if(subject == null) {
            return;
        }
        CrowUser user = (CrowUser) SecurityUtils.getSubject().getPrincipal();
        if(user == null) {
            return;
        }

        List<FilterItem> filterItems = body.getFilterItems();
        if(body.getTargetEntity().isAssignableFrom(CrowOrgLimitedEntity.class)
            || body.getTargetEntity().isAnnotationPresent(OrganizationLimited.class)
        ) {
            filterItems.add(new FilterItem(
                    "organizationId", user.getOrganizationId()
            ));
        }

        body.setFilterItems(filterItems);
    }

}
